const express = require('express')
const Router = express.Router();
const fs = require("fs");
const path = require("path");
const multer = require('multer');
const mkdir = require("../config/mkdir")

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        //路径
       
        let url = req.body.url//前端指定路径
        mkdir.mkdirs(`../data/${url}`,(err)=>{
            // console.log(err)
        })
        cb(null, `./data/${url}`)
    },
    filename: function (req, file, cb) {
        let name  = req.body.name//把命名的给前端决定
        if(req.body.type == 3){
            name  = req.body.name+new Date().getTime()
        }
        cb(null, name+file.originalname.replace(/.*\./,'.'))
    }
})
var upload = multer({ storage: storage })

Router.post('/file/upload', upload.single('file'), function (req, res, next) {
    res.send({path:req.body.url,filename:req.file.filename})
})


var storage1 = multer.diskStorage({
    destination: function (req, file, cb) {
        //路径   
        mkdir.mkdirs(`../data/tech`,(err)=>{
            // console.log(err)
        })
        cb(null, `./data/tech`)
    },
    filename: function (req, file, cb) {
        cb(null, new Date().getTime()+file.originalname.replace(/.*\./,'.'))
    }
})
var myupload = multer({ storage: storage1 })

Router.post('/file/uploadtech', myupload.single('image'), function (req, res, next) {
    res.send({path:'tech',filename:req.file.filename})
})










Router.post('/file/delete',(req, res) =>{
    fs.unlinkSync(path.join(__dirname,"../data/"+req.body.path+"/"+req.body.filename));
    res.send({status:200})
})

module.exports = Router;